package com.zeus.core.log.config;

import com.zeus.common.log.ZeusLoggerConfig;
import com.zeus.core.log.appender.Log4j2MonitorAppender;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Log4j配置信息
 *
 * @author f1ybear_wang 2021/6/3  0:18
 */
public class Log4j2Config {

    private final static Logger log = LoggerFactory.getLogger(Log4j2Config.class);

    private final static AtomicBoolean initialized = new AtomicBoolean(false);

    /**
     * Log4j配置信息初始化
     *
     * @return 是否初始化成功
     * @author f1ybear_wang 2021/6/3 0:17
     */
    public static boolean init() {
        try {
            if(initialized.compareAndSet(false,true)){
                // 获取 Log4j2 的 LoggerContext 和 Configuration
                LoggerContext context = (LoggerContext) LogManager.getContext(false);
                Configuration config = context.getConfiguration();

                // 创建 PatternLayout 用于定义日志输出格式
                PatternLayout layout = PatternLayout.newBuilder()
                                                    .build();

                Log4j2MonitorAppender log4j2MonitorAppender = new Log4j2MonitorAppender(layout);

                log4j2MonitorAppender.start();

                // 将 Appender 添加到配置中
                config.addAppender(log4j2MonitorAppender);

                // 获取根 LoggerConfig
                LoggerConfig rootLoggerConfig = config.getRootLogger();
                // 将 Appender 关联到根 LoggerConfig
                rootLoggerConfig.addAppender(log4j2MonitorAppender, Level.WARN, null);
                // 更新配置
                context.updateLoggers();
                if (log.isInfoEnabled() && ZeusLoggerConfig.needEnableLogger()) {
                    log.info(">>> Zeus日志监控模块, into LogMonitorApplicationListener，log4j2日志监控配置已经注入appender");
                }
                return true;
            }
        } catch (Throwable ignored) {
            // 忽略
        }
        return false;
    }

    public AtomicBoolean getInitialized() {
        return initialized;
    }
}
